<template>
  <div class="experiments">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">实验项目</h1>
        <p class="page-subtitle">通过实践项目掌握前端开发技能</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-section">
      <div class="container">
        <el-row :gutter="20">
          <!-- 左侧导航 -->
          <el-col :xs="24" :sm="6" :md="5">
            <div class="sidebar">
              <div class="sidebar-header">
                <h3>实验章节</h3>
                <el-tag type="info" size="small">共12章</el-tag>
              </div>
              <el-menu
                :default-active="activeChapter.toString()"
                class="chapter-menu"
                @select="handleChapterSelect"
              >
                <el-menu-item
                  v-for="chapter in chapters"
                  :key="chapter.id"
                  :index="chapter.id.toString()"
                >
                  <div class="menu-item-content">
                    <div class="chapter-info">
                      <span class="chapter-title">{{ chapter.title }}</span>
                      <!-- <span class="chapter-subtitle">{{ chapter.subtitle }}</span> -->
                    </div>
                    <el-badge 
                      :value="chapter.experiments.length" 
                      class="chapter-badge"
                      type="primary"
                    />
                  </div>
                </el-menu-item>
              </el-menu>
            </div>
          </el-col>

          <!-- 右侧内容 -->
          <el-col :xs="24" :sm="18" :md="19">
            <div class="content-card">
              <div class="content-header">
                <div class="chapter-info">
                  <h2>{{ currentChapter?.title }}</h2>
                  <p>{{ currentChapter?.description }}</p>
                </div>
                <div class="chapter-stats">
                  <el-tag type="success">{{ currentChapter?.experiments.length }} 个实验</el-tag>
                  <el-tag type="warning">{{ currentChapter?.difficulty }}</el-tag>
                </div>
              </div>

              <!-- 实验列表 -->
              <div class="experiments-list">
                <div 
                  v-for="experiment in currentChapter?.experiments"
                  :key="experiment.id"
                  class="experiment-card"
                  @click="selectExperiment(experiment)"
                >
                  <div class="experiment-header">
                    <div class="experiment-icon">
                      <el-icon :size="24" :color="experiment.completed ? '#67c23a' : '#909399'">
                        <component :is="experiment.completed ? 'CircleCheck' : 'Clock'" />
                      </el-icon>
                    </div>
                    <div class="experiment-info">
                      <h4>{{ experiment.title }}</h4>
                      <p>{{ experiment.description }}</p>
                    </div>
                    <div class="experiment-meta">
                      <el-tag :type="getDifficultyType(experiment.difficulty)" size="small">
                        {{ experiment.difficulty }}
                      </el-tag>
                      <span class="duration">{{ experiment.duration }}</span>
                    </div>
                  </div>
                  
                  <div class="experiment-content" v-if="selectedExperiment?.id === experiment.id">
                    <el-divider />
                    
                    <!-- 实验内容渲染 -->
                    <div class="markdown-content" v-html="renderMarkdown(experiment.content)"></div>
                    
                    <!-- 实验操作 -->
                    <div class="experiment-actions">
                      <el-button 
                        type="primary" 
                        @click="startExperiment(experiment)"
                        :disabled="experiment.completed"
                      >
                        {{ experiment.completed ? '已完成' : '开始实验' }}
                      </el-button>
                      <el-button @click="downloadResources(experiment)">
                        下载资源
                      </el-button>
                      <el-button 
                        v-if="experiment.completed"
                        type="success"
                        @click="viewSolution(experiment)"
                      >
                        查看答案
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 实验详情对话框 -->
    <el-dialog 
      v-model="showExperimentDetail" 
      :title="currentExperiment?.title" 
      width="90%"
      class="experiment-dialog"
    >
      <div v-if="currentExperiment" class="experiment-detail">
        <div class="detail-header">
          <div class="detail-meta">
            <el-tag :type="getDifficultyType(currentExperiment.difficulty)">
              {{ currentExperiment.difficulty }}
            </el-tag>
            <span class="duration">预计时间: {{ currentExperiment.duration }}</span>
          </div>
        </div>
        
        <el-tabs v-model="activeTab">
          <el-tab-pane label="实验说明" name="description">
            <div class="markdown-content" v-html="renderMarkdown(currentExperiment.content)"></div>
          </el-tab-pane>
          
          <el-tab-pane label="代码编辑" name="code">
            <div class="code-editor">
              <el-input
                v-model="userCode"
                type="textarea"
                :rows="20"
                placeholder="在这里编写你的代码..."
                class="code-textarea"
              />
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="预览效果" name="preview">
            <div class="preview-container">
              <iframe 
                ref="previewFrame"
                class="preview-frame"
                sandbox="allow-scripts allow-same-origin"
              ></iframe>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="提交作业" name="submit">
            <div class="submit-section">
              <el-form :model="submitForm" label-width="100px">
                <el-form-item label="作业文件">
                  <el-upload
                    class="upload-demo"
                    drag
                    action="#"
                    multiple
                    :auto-upload="false"
                    :file-list="fileList"
                    @change="handleFileChange"
                  >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持 .html, .css, .js, .zip 格式文件
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
                
                <el-form-item label="实验总结">
                  <el-input
                    v-model="submitForm.summary"
                    type="textarea"
                    :rows="4"
                    placeholder="请简要总结本次实验的收获和遇到的问题..."
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="submitExperiment">
                    提交实验
                  </el-button>
                  <el-button @click="saveProgress">
                    保存进度
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      
      <template #footer>
        <el-button @click="showExperimentDetail = false">关闭</el-button>
        <el-button type="primary" @click="runCode">运行代码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCheck, Clock, UploadFilled } from '@element-plus/icons-vue'

// 加载markdown文件的方法
const loadMarkdownContent = async (filePath) => {
  try {
    const response = await fetch(`/src/contents/${filePath}`)
    if (response.ok) {
      return await response.text()
    }
    return '内容加载失败'
  } catch (error) {
    console.error('加载markdown文件失败:', error)
    return '内容加载失败'
  }
}

// 响应式数据
const activeChapter = ref(1)
const selectedExperiment = ref(null)
const showExperimentDetail = ref(false)
const currentExperiment = ref(null)
const activeTab = ref('description')
const userCode = ref('')
const fileList = ref([])
const submitForm = ref({
  summary: ''
})
const previewFrame = ref(null)

// 章节数据
const chapters = ref([
  {
    id: 1,
    title: '第1章 HTML基础',
    subtitle: 'HTML标签与结构',
    description: '学习HTML基础语法，掌握常用标签的使用方法，理解网页结构的构建原理。',
    difficulty: '初级',
    experiments: [
      {
        id: 1,
        title: '个人简历页面制作',
        description: '使用HTML标签创建一个个人简历页面',
        difficulty: '初级',
        duration: '2小时',
        completed: false,
        contentFile: 'experiment-1-personal-resume.md',
        content: ''
      },
      {
        id: 2,
        title: '表格与表单设计',
        description: '创建包含表格和表单的网页',
        difficulty: '初级',
        duration: '1.5小时',
        completed: true,
        contentFile: 'experiment-2-table-form.md',
        content: ''
      }
    ]
  },
  {
    id: 2,
    title: '第2章 CSS样式',
    subtitle: '样式与布局',
    description: '学习CSS样式语法，掌握页面美化和布局技术。',
    difficulty: '初级',
    experiments: [
      {
        id: 3,
        title: '响应式网页布局',
        description: '使用CSS创建响应式布局',
        difficulty: '中级',
        duration: '3小时',
        completed: false,
        contentFile: 'experiment-3-responsive-layout.md',
        content: ''
      }
    ]
  },
  {
    id: 3,
    title: '第3章 JavaScript基础',
    subtitle: '交互与逻辑',
    description: '学习JavaScript基础语法，实现网页交互功能。',
    difficulty: '中级',
    experiments: [
      {
        id: 4,
        title: '计算器应用开发',
        description: '使用JavaScript开发一个简单的计算器',
        difficulty: '中级',
        duration: '4小时',
        completed: false,
        contentFile: 'experiment-4-calculator.md',
        content: ''
      }
    ]
  }
  // 可以继续添加更多章节...
])

// 计算属性
const currentChapter = computed(() => {
  return chapters.value.find(chapter => chapter.id === activeChapter.value)
})

// 方法
const handleChapterSelect = (key) => {
  activeChapter.value = parseInt(key)
  selectedExperiment.value = null
}

const selectExperiment = async (experiment) => {
  if (selectedExperiment.value?.id === experiment.id) {
    selectedExperiment.value = null
  } else {
    // 如果content为空且有contentFile，则加载markdown文件
    if (!experiment.content && experiment.contentFile) {
      experiment.content = await loadMarkdownContent(experiment.contentFile)
    }
    selectedExperiment.value = experiment
  }
}

const startExperiment = async (experiment) => {
  currentExperiment.value = experiment
  
  // 如果content为空且有contentFile，则加载markdown文件
  if (!experiment.content && experiment.contentFile) {
    experiment.content = await loadMarkdownContent(experiment.contentFile)
  }
  
  showExperimentDetail.value = true
  activeTab.value = 'description'
  userCode.value = experiment.startCode || ''
}

const getDifficultyType = (difficulty) => {
  const types = {
    '初级': 'success',
    '中级': 'warning',
    '高级': 'danger'
  }
  return types[difficulty] || 'info'
}

const renderMarkdown = (content) => {
  // 简单的Markdown渲染（实际项目中建议使用专业的Markdown解析库）
  return content
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
}

const runCode = () => {
  if (!userCode.value.trim()) {
    ElMessage.warning('请先编写代码')
    return
  }
  
  // 在预览框中运行代码
  const iframe = previewFrame.value
  if (iframe) {
    const doc = iframe.contentDocument || iframe.contentWindow.document
    doc.open()
    doc.write(userCode.value)
    doc.close()
  }
  
  activeTab.value = 'preview'
  ElMessage.success('代码运行成功')
}

const handleFileChange = (file, fileList) => {
  // 处理文件上传
}

const submitExperiment = () => {
  if (!submitForm.value.summary.trim()) {
    ElMessage.warning('请填写实验总结')
    return
  }
  
  // 提交实验逻辑
  currentExperiment.value.completed = true
  ElMessage.success('实验提交成功')
  showExperimentDetail.value = false
}

const saveProgress = () => {
  // 保存进度逻辑
  ElMessage.success('进度保存成功')
}

const downloadResources = (experiment) => {
  // 下载实验资源
  ElMessage.info('开始下载实验资源')
}

const viewSolution = (experiment) => {
  // 查看实验答案
  ElMessage.info('查看实验答案')
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.content-section {
  padding: 40px 0;
  min-height: calc(100vh - 200px);
}

.sidebar {
  position: sticky;
  top: 20px;
  height: calc(100vh - 140px); /* 减去页面头部高度和一些边距 */
  overflow-y: auto;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px 8px 0 0;
  border-bottom: 1px solid #eee;
}

.sidebar-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.2rem;
}

.chapter-menu {
  border: none;
  border-radius: 0 0 8px 8px;
}

.menu-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.chapter-info {
  flex: 1;
}

.chapter-title {
  display: block;
  font-weight: 600;
  margin-bottom: 4px;
}

.chapter-subtitle {
  display: block;
  font-size: 12px;
  color: #909399;
}

.chapter-badge {
  margin-left: 10px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 30px;
  border-bottom: 1px solid #eee;
}

.content-header .chapter-info h2 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.content-header .chapter-info p {
  margin: 0;
  color: #7f8c8d;
  line-height: 1.6;
}

.chapter-stats {
  display: flex;
  gap: 10px;
}

.experiments-list {
  padding: 20px 30px;
}

.experiment-card {
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.experiment-card:hover {
  background: #e3f2fd;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.experiment-header {
  display: flex;
  align-items: center;
  padding: 20px;
  gap: 15px;
}

.experiment-icon {
  flex-shrink: 0;
}

.experiment-info {
  flex: 1;
}

.experiment-info h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.1rem;
}

.experiment-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.experiment-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.duration {
  font-size: 0.85rem;
  color: #909399;
}

.experiment-content {
  padding: 0 20px 20px;
}

.markdown-content {
  line-height: 1.8;
  color: #2c3e50;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3 {
  color: #2c3e50;
  margin: 20px 0 15px 0;
}

.markdown-content code {
  background: #f1f2f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

.experiment-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.experiment-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.detail-header {
  margin-bottom: 20px;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 15px;
}

.code-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.code-textarea {
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.code-textarea :deep(.el-textarea__inner) {
  border: none;
  border-radius: 0;
  font-family: 'Courier New', monospace;
}

.preview-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  height: 400px;
}

.preview-frame {
  width: 100%;
  height: 100%;
  border: none;
}

.submit-section {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .chapter-stats {
    align-self: stretch;
  }
  
  .experiment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .experiment-meta {
    align-items: flex-start;
    flex-direction: row;
  }
  
  .experiment-actions {
    flex-direction: column;
  }
  
  .sidebar {
    position: static;
    margin-bottom: 20px;
  }
}
</style>